#include "IpV4Address.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include "BytesEndian.h"
#include "SocketOpt.h"
#include "Util.h"
namespace xncc {
namespace foundation {

    IpV4Address::IpV4Address(const std::string& addr, int protocol) : protocol_(protocol)
    {
        auto addrVec = shared::StrBusi::split(addr, ":");
        auto port    = static_cast<uint16_t>(std::stoi(addrVec[1]));
        shared::memZero(addr_);
        addr_.sin_family = AF_INET;
        addr_.sin_port   = hostToNetwork16(port);
        if (::inet_pton(AF_INET, addrVec[0].data(), &addr_.sin_addr) <= 0) {
            throw shared::logic_exception(std::string("is not valid ipv4 addr ") + shared::strerror_tl(errno));
        }
    }

    IpV4Address::IpV4Address(const struct sockaddr_in& addr, int protocol) : addr_(addr), protocol_(protocol) {}

    IpV4Address::IpV4Address(int protocol) : protocol_(protocol) {}

    IpV4Address::~IpV4Address() = default;
    std::string IpV4Address::toIpPort() const { return SocketOpt::toIpPort(getSockAddr()); }

    std::string IpV4Address::toIp() const { return SocketOpt::toIp(getSockAddr()); }

    uint16_t IpV4Address::toPort() const { return networkToHost16(addr_.sin_port); }
}  // namespace foundation
}  // namespace xncc